<template>
	<el-dialog :title="title" width="600" v-model="visible" :close-on-click-modal="false" draggable>
		<el-form ref="dialogFormRef" label-position="left" :model="dataForm" :rules="dataRules" label-width="100px" v-loading="loading">
			<el-row :gutter="20">
				<el-col :span="24" class="mb20">
					<el-form-item label="图层组命名" prop="geoLayerGroupName">
						<el-input
							:disabled="title === '编辑图层组'"
							v-model="dataForm.geoLayerGroupName"
							clearable
							placeholder="请输入图层组名称(仅支持英文)"
						></el-input>
					</el-form-item>
				</el-col>
				<el-col :span="24" class="mb20">
					<el-form-item label="图层组说明" prop="layerGroupRemarks">
						<el-input v-model="dataForm.layerGroupRemarks" clearable placeholder="请输入图层组说明"></el-input>
					</el-form-item>
				</el-col>
				<el-col :span="12" class="mb20">
					<el-form-item label="所属项目" prop="nameSpace">
						<el-select v-model="dataForm.nameSpace" :suffix-icon="IconDropDown" placeholder="选择所属项目">
							<el-option v-for="item in projectOptions" :key="item.value" :label="item.label" :value="item.value" />
						</el-select>
					</el-form-item>
				</el-col>
				<el-col :span="12" class="mb20">
					<el-form-item label="是否启用" prop="status"> <el-switch v-model="dataForm.status" :active-value="1" :inactive-value="0" /></el-form-item>
				</el-col>
				<el-col :span="24" class="mb20">
					<el-table
						class="table-style-one"
						:data="dataForm.layerVoList"
						:cell-style="tableStyle.childrenCellStyle"
						:header-cell-style="tableStyle?.childrenHeaderCellStyle"
					>
						<el-table-column label="层级" prop="name">
							<template #default="scope">
								<img
									v-if="checkAdjacentObject(dataForm.layerVoList, scope.row.layerUrl, 'layerUrl', 'after')"
									@click="moveItem(scope.$index, 'up')"
									class="inline-block cursor-pointer"
									src="/@/assets/icons/up-able.svg"
								/>
								<img v-else class="inline-block cursor-not-allowed" src="/@/assets/icons/up-disable.svg" />
								<img
									v-if="checkAdjacentObject(dataForm.layerVoList, scope.row.layerUrl, 'layerUrl', 'before')"
									@click="moveItem(scope.$index, 'down')"
									class="inline-block cursor-pointer ml8"
									src="/@/assets/icons/down-able.svg"
								/>
								<img v-else class="inline-block cursor-not-allowed ml8" src="/@/assets/icons/down-disable.svg" />
							</template>
						</el-table-column>
						<el-table-column prop="storeType" label="类型" width="100">
							<template #default="scope">
								<div class="type-tag" :style="typeColor[scope.row.storeType]">{{ getOptName(typeDict, scope.row.storeType) }}</div>
							</template>
						</el-table-column>
						<el-table-column label="图层名称" prop="layerName" show-overflow-tooltip width="120" />
						<el-table-column label="图层说明" prop="layerRemarks" show-overflow-tooltip />
						<el-table-column label="预览">
							<template #default="scope">
								<span @click="openLayerShow(scope.row.layerUrl)" class="jColor">查看</span>
							</template>
						</el-table-column>
						<el-table-column label="管理">
							<template #header>
								<img class="cursor-pointer inline-block" src="/@/assets/icons/circle-plus.svg" @click="addLayerToGroup()" />
							</template>
							<template #default="scope">
								<i class="iconfont icon-shanchu jColor" @click="handleDelete(scope.row, dataForm.layerVoList)"></i>
							</template>
						</el-table-column>
					</el-table>
				</el-col>
			</el-row>
		</el-form>
		<template #footer>
			<span class="dialog-footer">
				<el-button class="wid100" type="primary" @click="onSubmit" :disabled="loading">{{ $t('common.publish') }}</el-button>
			</span>
		</template>
		<addLayerDialog @addLayer="addLayer" ref="addLayerDialogRef"></addLayerDialog>
	</el-dialog>
</template>

<script setup lang="ts" name="layerGroupDialog">
import { useI18n } from 'vue-i18n';
import { useMessage } from '/@/hooks/message';
import { BasicTableProps, useTable } from '/@/hooks/table';
import DropDown from '/@/assets/icons/drop-down.svg';
import { checkAdjacentObject } from '/@/utils/arrayOperation';
import { addLayerGroup, updataLayerGroup } from '/@/api/resource/layerGroups';
import { useUserInfo } from '/@/stores/userInfo';

// 定义子组件向父组件传值/事件
const emit = defineEmits(['refresh']);
const { t } = useI18n();
// 引入组件
const addLayerDialog = defineAsyncComponent(() => import('./addLayerToGroup.vue'));

// 定义变量内容
const title = ref();
const visible = ref(false);
const loading = ref(false);
const dialogFormRef = ref();
const addLayerDialogRef = ref();
const projectOptions = computed(() => {
	return useUserInfo().userInfos.projectList;
});
const typeDict = ref([
	{
		text: '矢量',
		value: 'dataStore',
	},
	{
		text: '栅格',
		value: 'coverageStore',
	},
]);
const typeColor = ref<any>({
	dataStore: { background: '#c1deff', color: '#499dff' },
	coverageStore: { background: '#dad7ff', color: '#826EFF' },
});
// 定义需要的数据
const dataForm = reactive({
	geoLayerGroupName: '',
	layerGroupRemarks: '',
	nameSpace: '',
	status: '',
	layerVoList: [],
});

const tableState: BasicTableProps = reactive<BasicTableProps>({
	queryForm: {
		menuName: '',
	},
	isPage: false,
});

const IconDropDown = {
	render: () => {
		return h('img', { src: DropDown });
	},
};

const { tableStyle } = useTable(tableState);

const checkData = (rule?: any, value?: any, callback?: any) => {
	if (value) {
		if (/[\u4E00-\u9FA5]/g.test(value)) {
			callback(new Error('图层组名称不能输入汉字!'));
		} else {
			callback();
		}
	}
	callback();
};

// 表单校验规则
const dataRules = reactive({
	geoLayerGroupName: [
		{ required: true, message: '图层组名不能为空', trigger: 'blur' },
		{ validator: checkData, trigger: 'blur' },
	],
	layerGroupRemarks: [{ required: true, message: '图层说明不能为空', trigger: 'blur' }],
	nameSpace: [{ required: true, message: '所属项目不能为空', trigger: 'blur' }],
});

const getOptName = (dictList: Array<object>, optCode: String) => {
	let dict: any = dictList.find((value: any) => value.value === optCode);
	return dict ? dict.text : '';
};

const moveItem = (index?: any, direction?: any) => {
	if ((direction === 'up' && index > 0) || (direction === 'down' && index < dataForm.layerVoList.length - 1)) {
		const offset = direction === 'up' ? -1 : 1;
		const temp = dataForm.layerVoList[index + offset];
		dataForm.layerVoList[index + offset] = dataForm.layerVoList[index];
		dataForm.layerVoList[index] = temp;
	}
};

const addLayer = (layerInfo?: any) => {
	dataForm.layerVoList.push(layerInfo);
};

//打开添加图层弹框
const addLayerToGroup = () => {
	addLayerDialogRef.value.dataForm.nameSpace = dataForm.nameSpace;
	addLayerDialogRef.value.openDialog('add', dataForm.nameSpace);
};

// 查看图层iframe
const openLayerShow = (layerUrl: any) => {
	/* iframeUrl.value = layerUrl;
	showIframe.value = true; */
	window.open(layerUrl, '_blank');
};

// 打开弹窗
const openDialog = (type: string, row?: any) => {
	title.value = '创建图层组';
	dataForm.geoLayerGroupName = '';
	visible.value = true;

	nextTick(() => {
		// 数据重置
		dialogFormRef.value.resetFields();
		dataForm.status = '0';
		dataForm.layerVoList = [];

		if (row?.geoLayerGroupName && type === 'edit') {
			title.value = '编辑图层组';

			// 获取表单信息
			Object.assign(dataForm, {
				geoLayerGroupName: row.geoLayerGroupName,
				layerGroupRemarks: row.layerGroupRemarks,
				nameSpace: row.nameSpace,
				status: row.status,
				layerVoList: row.layerVoList,
			});
			console.log(dataForm.status, '状态');
		}
	});
};

const handleDelete = (row?: any, parentRow?: any) => {
	dataForm.layerVoList = parentRow.filter((obj: any) => obj.layerUrl !== row.layerUrl);
};

// 保存数据
const onSubmit = async () => {
	const valid = await dialogFormRef.value.validate().catch(() => {});
	if (!valid) return false;

	try {
		loading.value = true;
		// 数据处理
		const newArray = dataForm.layerVoList.map((obj: any) => {
			return { nameSpace: obj.nameSpace, title: obj.layerName };
		});
		const params = {
			nameSpace: dataForm.nameSpace,
			layerGroupName: dataForm.geoLayerGroupName,
			status: dataForm.status,
			layerGroupRemarks: dataForm.layerGroupRemarks,
			layerList: newArray,
		};
		title.value === '编辑图层组' ? await updataLayerGroup(params) : await addLayerGroup(params);
		useMessage().success(t(title.value === '编辑图层组' ? 'common.editSuccessText' : 'common.publishSuccessText'));
		visible.value = false;
		emit('refresh');
	} catch (err: any) {
		useMessage().error(err.msg);
	} finally {
		loading.value = false;
	}
};

// 暴露变量 只有暴漏出来的变量 父组件才能使用
defineExpose({
	openDialog,
});
</script>

<style scoped lang="scss">
.dialog-footer {
	display: flex;
	justify-content: center;
}

.blue-card {
	margin: 5px;
	padding: 10px;
	border-radius: 8px;
	background: #eaf1ff;
}
</style>
